const fs = require('fs');
const path = require('path');
var tools = require('../../../libs/tools');
var config = require(tools.rootPath + 'config');
var { connection, pool, model } = require(tools.rootPath + 'libs/model');

var controller = require(tools.rootPath + 'libs/controller.js');

const formidable = require('formidable');

module.exports = class extends controller {
    constructor() {
        super();
    }
    //注释掉app.js中的express-fileupload
    index(req, res) {
        console.log(tools.controllerPath);
        res.render(req.TPL);
    }
    async up_img(req, res) {
        if (req.ispost) {
            const form = formidable({ multiples: false });

            /*
        {
          "fields": {
            "type": "dbk_cover",
            "callback": "crop_200_200"
          },
          "files": {
            "sampleFile": {
              "size": 481978,
              "path": "/tmp/upload_1789451950572f4da6c33a7338c782de",
              "name": "big_cats085.jpg",
              "type": "image/jpeg",
              "mtime": "2020-05-29T03:53:53.765Z"
            }
          }
        }
            * */
            function p() {
                return new Promise((resolve, reject) => {
                    form.parse(req, (err, fields, files) => {
                        if (err) {
                            reject([]);
                            return;
                        } else {
                            resolve([fields, files]);
                        }

                    });
                });
            }

            let r = await p();

            if (r.length == 0) {
                res.end(`<script>alert('上传失败！');history.back();</script>`);
                return;
            }
            let [fields, files] = r;
            //console.log(fields, files);

            if (typeof (files.sampleFile) == 'undefined') {
                res.end(`<script>alert('请选择一个文件！');history.back();</script>`);
                return;
            }

            let cls = '';
            let i = 0;
            let callback = fields.callback;
            let uniq = '';

            let extensions = [
                'jpg',
                'png',
                'gif',
            ];


            let file = files.sampleFile;


            //判断文件大小
            let size = file.size;
            if (size > 10 * 1024 * 1024) {
                res.end(`<script>alert('文件超出最大大小！');history.back();</script>`);
                return;
            }
            //判断文件后缀
            let filename = file.name;
            let ext = tools.extension(filename);
            if (!tools.in_array(ext, extensions)) {
                res.end(`<script>alert('文件类型不正确！');history.back();</script>`);
                return;
            }
            //创建文件夹
            let destination = tools.uploadsPath + tools.date('', 'Y/M/D') + '/' + tools.date('', 'YMDhms') + tools.randomNum(100000, 999999) + '.' + ext;
            if (!fs.existsSync(path.dirname(destination))) {
                fs.mkdirSync(path.dirname(destination), { recursive: true });
            }
            //复制文件
            let url = destination.replace(tools.rootPath + 'public', '');
            url = url.replace(/\\/g, '/');
            fs.copyFileSync(file.path, destination);
            if (!fs.existsSync(destination)) {
                res.end(`<script>alert('文件写入失败！');history.back();</script>`);
                return;
            }
            res.end(`<script>alert('上传成功！');window.parent.${callback}('${url}');</script>`);
            return;
        }
        let callback = req.query.callback;
        res.render(req.TPL, { callback: callback });
    }
}